#!/usr/bin/perl
use lib "$ENV{MYSQL_DRAW}/lib";
use MyTools;
use strict;
use Data::Dumper;
use Getopt::Long;
use DBI;

my ($project_name, $subject_name, $debug);
my @argv = @ARGV;
&GetOptions("debug!"=> \$debug,
            "project_name=s" => \$project_name,
            "subject_name=s" => \$subject_name);

if ((!$project_name) || (!$subject_name)) {
	die "usage: $0 --project_name PSP --subject_name PSP7020 [--debug]\n(use --debug to preview what would be inserted into mysql table)\n";
}

my $table = `basename $0 .pl | sed s/insert//`;
chomp($table);
printf STDERR "Inserting $subject_name into table $table\n";
if ($debug) {
	printf "Debug mode. The following are aguments\n";
}
else {
	my $newid=driver();
	printf STDERR "${project_name}_${subject_name} %s\n", ($newid) ? "inserted into $table with SBID=$newid" : "already in $table\n\n";
}

sub driver {
	my $dbh = DBI->connect($ENV{dbi1}, $ENV{dbi2}, $ENV{dbi3}) or die "Couldn't connect to database: " . DBI->errstr;
	my $project_id = MyTools::fetchrow1col1_arrayref($dbh, "select PID from Project where ", {'ProjectName' => $project_name}) or die "Project $project_name not found\n";
	my $record_present = MyTools::fetchrow1col1_arrayref($dbh, "select SBID from $table where ", {'ProjectID' => $project_id, 'SubjectName' => $subject_name});
	if (defined($record_present)) {
		printf STDERR "Existing SBID=%d ", $record_present;
		return 0;
	}
	my $sth = $dbh->prepare("INSERT INTO $table (ProjectID,SubjectName) VALUES (?,?)") or die "Couldn't prepare statement: " . $dbh->errstr;
	$sth->execute($project_id, $subject_name) or die "Couldn't execute statement: " . $sth->errstr;
	return MyTools::fetchrow1col1_arrayref($dbh, "select SBID from $table where ", {'ProjectID' => $project_id, 'SubjectName' => $subject_name});
}
